package com.wswy.wzcx.ui.main.ad

import android.app.Activity
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.graphics.drawable.ColorDrawable
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.blankj.utilcode.util.SPUtils
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTBannerAd
import com.bytedance.sdk.openadsdk.TTInteractionAd
import com.facebook.drawee.view.SimpleDraweeView
import com.qq.e.ads.nativ.ADSize
//import com.qq.e.ads.banner.ADSize
//import com.qq.e.ads.banner.BannerView
import com.wswy.wzcx.BuildConfig
import com.wswy.wzcx.R
import com.wswy.wzcx.model.AdConfigs
import com.wswy.wzcx.model.AdModel
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.module.AllAdConfLoader
import com.wswy.wzcx.module.RuntimeContext
import com.wswy.wzcx.module.ad.AdConfigLoader
import com.wswy.wzcx.module.ad.TTAdManagerHolder
import com.wswy.wzcx.module.base.BaseViewModel
import com.wswy.wzcx.module.base.SingleLiveData
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.utils.FrescoUtils
import com.wswy.wzcx.utils.ImageUtils
import com.wswy.wzcx.utils.RxUtils
import io.reactivex.MaybeObserver
import io.reactivex.Single
import io.reactivex.SingleObserver
import io.reactivex.disposables.Disposable

class HomeAdViewModel : BaseViewModel() {

    companion object {
        private const val TAG = "HomeAdViewModel"


        private const val LAST_INTERACTION_AD = "last_ad_home_interaction"

    }

    //轮播广告
    private val adsBannerLiveData = MutableLiveData<List<AdItemVo>?>()

    //插屏广告
    private val adInteractionLiveData = SingleLiveData<AdItemVo?>()

    //悬浮广告
    private val adFloatLiveData = MutableLiveData<AdItemVo?>()

    //其它类型csj广告
    private val adMineBannerLiveData = SingleLiveData<AdItemVo?>()

    private val homeVpAdLiveData = SingleLiveData<List<AdModel?>?>()


    private var isLoadEnd = false

    fun loadAD(act:Activity){
        if (!isLoadEnd){
            isLoadEnd = true

            if (RuntimeContext.isPaidChannel()){
                loadPaidAd(act)
            }else{
                loadDefaultAd(act)
            }
        }

    }


    private fun loadDefaultAd(act: Activity){
        //加载默认广告配置
        AllAdConfLoader(act.applicationContext).loader {

            it.orNull()?.run {
                homeBannerAd?.run {
                    handleBannerAd(this,act)
                }

                homeDialogAd?.firstOrNull()?.run {
                    handleInteractionAd(this,act)
                }

                homeFloatAd?.firstOrNull()?.run {
                    handleFloatAd(this,act)
                }

                homevpAd?.run {
                    if (isNotEmpty()){
                        homeVpAdLiveData.postValue(this)
                    }
                }

                preLoadAd(this)

            }


        }
    }


    private fun loadPaidAd(act: Activity){
        //加载付费广告


        handleBannerAd(arrayListOf(AdModel().apply {
            type = AdModel.TTAD
        }),act)

        adMineBannerLiveData.postValue(AdItemVo(AdItemVo.TTAD,AdModel().apply {
            type = AdModel.TTAD
        }, View(act)))

    }


    private fun preLoadAd(cfg:AdConfigs){

        cfg.getPayAd()?.run {

            if (type == AdModel.SELF_AD){
                //自定义广告
                if (!TextUtils.isEmpty(imgUrl)){
                    FrescoUtils.downloadImage(imgUrl)
                }
            }
        }

        cfg.getWzcxAd()?.run {

            if (type == AdModel.SELF_AD){
                //自定义广告
                if (!TextUtils.isEmpty(imgUrl)){
                    FrescoUtils.downloadImage(imgUrl)
                }
            }
        }
    }


    //横幅banner
    private fun handleBannerAd(listAds:List<AdModel>,act: Activity){

        var ttadModel: AdModel? = null

        val list = arrayListOf<AdModel>()

        list.addAll(listAds)


        if (list.size != 1 && list.size < 3) {
            list.addAll(listAds)
            //list.addAll(listAds)
        }


        list.map {

            when(it.type){
                AdModel.SELF_AD -> {
                    AdItemVo(AdItemVo.SELF_IMG,it, SimpleDraweeView(act).apply {
                        hierarchy?.setPlaceholderImage(ColorDrawable(ContextCompat.getColor(context, R.color.dark_bg_color)))
                        ImageUtils.showImage(this,it.imgUrl)
                        val ad = it
                        onClick {
                            RouterUtils.startTarget(it.context,ad.linkTarget,ad.linkUrl)
                        }

                    })
                }
                AdModel.GDT -> {
                    ttadModel = it

                    null
//                    AdItemVo(AdItemVo.GDT_AD,it, BannerView(act, ADSize.BANNER,
//                            AdConfigLoader.gdtConfig.appId,
//                            AdConfigLoader.gdtConfig.bannerId).apply {
////                        setRefresh(0)
////                        loadAD()
//                    })

                }
                AdModel.TTAD -> {

                    ttadModel = it

                    null

                }
                else -> null
            }

        }.filterNotNull().toMutableList().let {

            val ads = it

            ttadModel?.let {ttad ->

                val adSlot = AdSlot.Builder()
                        .setCodeId(AdConfigLoader.csjConfig.bannerId)
                        .setSupportDeepLink(true)
                        .setImageAcceptedSize(600, 150)
                        .setAdCount(1)
                        .build()
                TTAdManagerHolder.getInstance(act.applicationContext).createAdNative(act).loadBannerAd(adSlot,object : TTAdNative.BannerAdListener{
                    override fun onBannerAdLoad(ad: TTBannerAd?) {

                        ad?.bannerView?.run {

                            ads.add(AdItemVo(AdItemVo.TTAD, ttad,this))
                        }

                        showAds(ads)
                    }

                    override fun onError(code: Int, message: String?) {


                        showAds(ads)

                    }

                })


            }?:kotlin.run {
                showAds(ads)
            }

        }


    }

    //弹窗
    private fun handleInteractionAd(adModel: AdModel,act: Activity){

        //加载插屏弹窗广告
        Single.just(adModel).map {

            if (it.showSelfAd() && !TextUtils.isEmpty(it.imgUrl)){
                FrescoUtils.preLoadBitmap(it.imgUrl,0,0)
            }

            it
        }.compose(RxUtils.io2main()).map {ad ->
           when(ad.type){
                //头条插屏广告,自行加载处理
                AdModel.TTAD -> {
                    AdItemVo(AdItemVo.TTAD, ad, View(act))
                }
                //自定义插屏广告
                else -> AdItemVo(AdItemVo.SELF_IMG, ad, SimpleDraweeView(act).apply {

                    ImageUtils.showImage(this,ad.imgUrl)

                    onClick {
                        RouterUtils.startTarget(it.context,ad.linkTarget,ad.linkUrl)
                    }

                })
            }
        }.subscribe(object : SingleObserver<AdItemVo>{

            override fun onSuccess(t: AdItemVo) {

                //判断弹窗是否可以展示，每天只展示一次

                val  last = SPUtils.getInstance().getLong(LAST_INTERACTION_AD,0)

                if (last == 0L || (System.currentTimeMillis() -last > 1000*60*60*24)){
                    SPUtils.getInstance().put(LAST_INTERACTION_AD,System.currentTimeMillis())
                    adInteractionLiveData.postValue(t)
                }


            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onError(e: Throwable) {
                Log.e(TAG, " --> ",e);
            }

        })




    }

    //悬浮
    private fun handleFloatAd(adModel: AdModel,act: Activity){


        Single.just(adModel).map {
            FrescoUtils.preLoadBitmap(it.imgUrl,0,0)
            it
        }.compose(RxUtils.io2main()).map {ad ->
            AdItemVo(AdItemVo.SELF_IMG, ad, SimpleDraweeView(act).apply {

                ImageUtils.showImage(this,ad.imgUrl)

                onClick {

                    RouterUtils.startTarget(it.context,ad.linkTarget,ad.linkUrl)
                }
            })
        }.subscribe(object : SingleObserver<AdItemVo>{

            override fun onSuccess(t: AdItemVo) {

                adFloatLiveData.postValue(t)

            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onError(e: Throwable) {
                Log.e(TAG, " --> ",e);
            }

        })



    }


    private fun showAds(ads:List<AdItemVo>){

        adsBannerLiveData.postValue(ads)

    }

    fun showTTADInteraction(act: Activity){
        val interactionId = AdConfigLoader.csjConfig.interactionId?:"903230589"
        val adSlot = AdSlot.Builder()
                .setCodeId(interactionId)
                .setSupportDeepLink(true)
                .setImageAcceptedSize(600, 900)
                .build()
        TTAdManagerHolder.getInstance(act.applicationContext)
                .createAdNative(act)
                .loadInteractionAd(adSlot,object :TTAdNative.InteractionAdListener{
                    override fun onInteractionAdLoad(ttInteractionAd: TTInteractionAd?) {

                        ttInteractionAd?.let {

                            if (!act.isFinishing){
                                it.showInteractionAd(act)
                            }

                        }
                    }

                    override fun onError(code: Int, message: String?) {
                        if (BuildConfig.DEBUG){
                            Log.e(TAG, "loadInteractionAd  --> $code   $message")
                        }
                    }

                })

    }

    fun loadBannerView(act: Activity,callback:((View)->Unit)){


        val adSlot = AdSlot.Builder()
                .setCodeId(AdConfigLoader.csjConfig.bannerId)
                .setSupportDeepLink(true)
                .setImageAcceptedSize(600, 150)
                .build()
        TTAdManagerHolder.getInstance(act.applicationContext)
                .createAdNative(act)
                .loadBannerAd(adSlot,object :TTAdNative.BannerAdListener{
                    override fun onBannerAdLoad(ad: TTBannerAd?) {
                        ad?.bannerView?.let {
                            callback.invoke(it)
                        }
                    }

                    override fun onError(code: Int, message: String?) {
                        if (BuildConfig.DEBUG){
                            Log.e(TAG, "loadBannerAd --> $code  $message")
                        }
                    }

                })
    }


    fun getAdsLiveData(): LiveData<List<AdItemVo>?> = adsBannerLiveData


    fun getAdInteractionLiveData():LiveData<AdItemVo?> = adInteractionLiveData

    fun getAdFloatLiveData():LiveData<AdItemVo?> = adFloatLiveData

    fun getMineAdBannerLiveData():LiveData<AdItemVo?> = adMineBannerLiveData

    fun getHomevpAdLiveData():LiveData<List<AdModel?>?> = homeVpAdLiveData
}